package com.example.server;

import com.example.core.raft.RaftServer;
import com.example.core.utils.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/*
 * @className: ServerFactory
 * @author: chentao
 * @date: 2025/2/21 下午2:49
 * @Version: 1.0
 * @description:
 */
@Service
public class RaftServerFactory implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private RaftServer server;

    @Value("${server.port}")
    private int port;

    @Override
    public void afterPropertiesSet() throws Exception {
        long serverId = IPUtils.combineIpAndPort(IPUtils.getLocalIP(), port);
        this.server = new RaftServer(String.valueOf(serverId));
        this.server.start();
    }

    @Override
    public void destroy() throws Exception {
        this.server.stop();
    }

    public RaftServer getServer() {
        return server;
    }
}
